package in.edupack.hibernate.criteria;

import java.util.Iterator;
import java.util.List;

import in.edupack.hibernate.pojo.Student;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;

/**
 * 
 * @author Bibek
 * The Criteria interface allows to create and execute object-oriented queries. 
 * It is powerful alternative to the HQL but has own limitations. 
 * Criteria Query is used mostly in case of multi criteria search screens, where HQL is not very effective.
 */
public class CriterialExample {
  public static void main(String[] args) {
	CriterialExample criterialExample = new CriterialExample();
	criterialExample.simpleExample();
}

private void simpleExample() {
	Session session  = null;
	SessionFactory factory = new Configuration().configure("in/edupack/hibernate/config/hbm-config.xml").buildSessionFactory();
	session = factory.openSession();
	
	Criteria crt = session.createCriteria(Student.class);
	//Customising Criteria these are optional this is similar to like condition in SQL/HQL
	crt.add(Restrictions.like("name", "B%"));
	//Restricts the max rows to 5
	crt.setMaxResults(5);
	//Between condition
	crt.add(Expression.between("age", new Integer(10),new Integer(20))); 
	//Similarly Data range condition can be applied
	crt.add(Expression.eq("id",new Integer(1)));		
	//Similar lt,gt can be applied
	//Also and/or condtion can be applied with expression
	
	List crtList = crt.list();
	
	Iterator<Student> it = crtList.iterator();
	while (it.hasNext())
	{
		Student std = it.next();
		System.out.println("ID "+std.getId() + " Name "+std.getName());
	}
	
	session.close();
}
}
